#include<mysql/mysql.h>
#include<iostream>
#include<string>
//#include<stdio.h>
using namespace std;


int main(){
  //1，初始化句柄
  MYSQL* _sql = mysql_init(NULL);
  if(!_sql){
    cout << "mysql init error" << endl;
    return -1;
  }

  //2.连接数据库服务器
  if((mysql_real_connect(_sql,"192.168.35.143","root","","OrderSystem",0,NULL,0))==NULL){
    printf("connect error:%s\n", mysql_error(_sql));
    mysql_close(_sql);
    return -1;
  }
  
  //3.设置客户端字符集
  int ret = mysql_set_character_set(_sql,"utf8");
  if(ret){
    printf("set character error:%s\n", mysql_error(_sql));
    mysql_close(_sql);
    return -1;
  }

  //4.选择操作数据库
  //5.执行语句
    //insert student values(2,'老刘', 20, now()); //--插入
    //const char* insert = "insert student values(2,'老刘', 20, now());";
    
    //const char* del = "delete from student where sn = 2;";

  const char* updata = "update student set name = '赵亮' where name = '李四'";
  ret = mysql_query(_sql,updata);
  if(ret != 0){
    printf("query error:%s\n", mysql_error(_sql));
    mysql_close(_sql);
    return -1; 
  } 
//#ifdef a
  //----查询
  const char* query = "select * from student;";
  ret = mysql_query(_sql,query);
  if(ret != 0){
    printf("query error:%s\n", mysql_error(_sql));
    mysql_close(_sql);
    return -1; 
  }
  //6若是查询则获取结果集
  MYSQL_RES* res = mysql_store_result(_sql);
  if(res  == NULL){
    printf("store result error:", mysql_error(_sql));
    return -1;
  }
  int row = mysql_num_rows(res);
  int col = mysql_num_fields(res);
  for(int i = 0; i < row; i++){
    MYSQL_ROW res_row = mysql_fetch_row(res);
    for(int j = 0; j < col; j++){
      printf("%-15s", res_row[j]);
    }
    cout << endl;
  }
  mysql_free_result(res);//释放结果集
//#endif

  //7.关闭接口
  mysql_close(_sql);
  return 0;
}
